import router from "./index";
import NProgress from "@/utils/nprogress.ts";
import { useUserStoreHook } from "@/store/module/useUserStore";
import { usePermissionStoreHook } from "@/store/module/usePermission";
import { getToken, setToken } from "@/utils/tokenTools";

// 白名单
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  console.log(from);
  NProgress.start();
  const userStore = useUserStoreHook();
  const PermissionStore = usePermissionStoreHook();
  const token = getToken();
  // 如果登录了
  if (token) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      // 判断是否请求了用户信息
      if (Object.getOwnPropertyNames(userStore.userInfo).length !== 0) {
        if (to.name === undefined) {
          next("/404");
        } else {
          next();
        }
      } else {
        try {
          await userStore.getUserInfo();
          PermissionStore.setRouter(userStore.userInfo?.powerKey);
          PermissionStore.dynamicRoutes.forEach((item: any) => {
            router.addRoute("root", item);
          });
          next({ ...to, replace: true });
        } catch (error) {
          // 移除token并跳转到登录页
          setToken("");
          // 重定向到登录页，
          next({ path: `/login?redirect=${to.fullPath}` });
        }
      }
    }
  } else {
    //   未登录
    //   如果在白名单里面，直接进入
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next({ path: `/login?redirect=${to.fullPath}` });
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
